/**
 * 段落生成Store
 * 管理段落生成状态、版本选择、混合等功能
 */

import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import {
  ParagraphData,
  ParagraphVersion,
  ParagraphStrategy,
  ParagraphMetrics,
} from '@/types/brainstorm';
import { paragraphGeneratorService } from '@/services/paragraph-generator.service';
import { useBrainstormStore } from './brainstorm.store';

interface ParagraphState {
  // 段落数据 - key为outlineNodeId
  paragraphs: Record<string, ParagraphData>;

  // 当前正在处理的节点ID
  currentNodeId: string | null;

  // 生成状态
  generating: boolean;
  paused: boolean;
  currentProgress: number; // 0-100

  // 待生成的节点ID列表
  pendingNodeIds: string[];

  // Actions
  startGeneration: (versionCount: number, strategies: ParagraphStrategy[]) => Promise<void>;
  pauseGeneration: () => void;
  resumeGeneration: () => void;
  stopGeneration: () => void;

  appendParagraphChunk: (nodeId: string, versionIndex: number, chunk: string) => void;
  completeParagraphVersion: (
    nodeId: string,
    versionIndex: number,
    metrics: ParagraphMetrics
  ) => void;
  setParagraphError: (nodeId: string, versionIndex: number, error: string) => void;

  selectVersion: (nodeId: string, versionIndex: number) => void;
  regenerateVersion: (
    nodeId: string,
    versionIndex: number,
    adjustments?: any
  ) => Promise<void>;
  mixVersions: (nodeId: string, selections: any[]) => Promise<void>;

  setCurrentNode: (nodeId: string | null) => void;
  clearParagraphs: () => void;
  removeParagraph: (nodeId: string) => void;

  // 内部方法
  generateSingleParagraph?: (
    nodeId: string,
    versionCount: number,
    strategies: ParagraphStrategy[]
  ) => Promise<void>;
}

export const useParagraphStore = create<ParagraphState>()(
  persist(
    (set, get) => ({
      paragraphs: {},
      currentNodeId: null,
      generating: false,
      paused: false,
      currentProgress: 0,
      pendingNodeIds: [],

      /**
       * 开始批量生成
       */
      startGeneration: async (versionCount, strategies) => {
        const { currentSession } = useBrainstormStore.getState();

        if (!currentSession || !currentSession.outline) {
          console.error('❌ [ParagraphStore] No outline available');
          return;
        }

        // 获取所有叶子节点（没有children的节点）
        const collectLeafNodes = (nodes: any[]): string[] => {
          const leafIds: string[] = [];
          nodes.forEach((node) => {
            if (!node.children || node.children.length === 0) {
              leafIds.push(node.id);
            } else {
              leafIds.push(...collectLeafNodes(node.children));
            }
          });
          return leafIds;
        };

        const leafNodeIds = collectLeafNodes(currentSession.outline.nodes);

        set({
          generating: true,
          paused: false,
          pendingNodeIds: leafNodeIds,
          currentProgress: 0,
        });

        console.log('🚀 [ParagraphStore] Starting batch generation:', {
          totalNodes: leafNodeIds.length,
          versionCount,
          strategies,
        });

        // 逐个节点生成
        for (let i = 0; i < leafNodeIds.length; i++) {
          const { paused, generating } = get();
          if (!generating) {
            console.log('⏹️ [ParagraphStore] Generation stopped');
            break;
          }

          while (paused) {
            // 暂停时等待
            await new Promise((resolve) => setTimeout(resolve, 500));
          }

          const nodeId = leafNodeIds[i];
          set({ currentNodeId: nodeId });

          await get().generateSingleParagraph!(nodeId, versionCount, strategies);

          // 更新进度
          const progress = Math.round(((i + 1) / leafNodeIds.length) * 100);
          set({ currentProgress: progress });
        }

        set({
          generating: false,
          currentNodeId: null,
          pendingNodeIds: [],
        });

        console.log('✅ [ParagraphStore] Batch generation completed');
      },

      /**
       * 生成单个段落
       */
      generateSingleParagraph: async (
        nodeId: string,
        versionCount: number,
        strategies: ParagraphStrategy[]
      ) => {
        const { currentSession } = useBrainstormStore.getState();
        if (!currentSession) return;

        // 查找节点
        const findNode = (nodes: any[], id: string): any => {
          for (const node of nodes) {
            if (node.id === id) return node;
            if (node.children) {
              const found = findNode(node.children, id);
              if (found) return found;
            }
          }
          return null;
        };

        const node = findNode(currentSession.outline?.nodes || [], nodeId);
        if (!node) {
          console.error('❌ [ParagraphStore] Node not found:', nodeId);
          return;
        }

        // 获取已生成的内容作为上下文
        const previousContent: string[] = [];
        const allParagraphs = get().paragraphs;
        Object.keys(allParagraphs).forEach((key) => {
          const para = allParagraphs[key];
          if (para.selectedVersionIndex >= 0) {
            previousContent.push(para.versions[para.selectedVersionIndex].content);
          }
        });

        // 初始化段落数据
        set((state) => ({
          paragraphs: {
            ...state.paragraphs,
            [nodeId]: {
              id: nodeId,
              outlineNodeId: nodeId,
              versions: strategies.slice(0, versionCount).map((strategy) => ({
                content: '',
                strategy,
                generating: true,
                aiScore: 0,
                wordCount: 0,
                metrics: {
                  relevance: 0,
                  readability: 0,
                  originality: 0,
                  coherence: 0,
                },
              })),
              selectedVersionIndex: -1,
              createdAt: new Date().toISOString(),
              updatedAt: new Date().toISOString(),
            },
          },
        }));

        // 调用生成服务
        await paragraphGeneratorService.generateParagraph(
          {
            sessionId: currentSession.id,
            outlineNodeId: nodeId,
            outlineNode: node,
            previousContent,
            versionCount,
            strategies,
          },
          // onChunk
          (versionIndex, chunk) => {
            get().appendParagraphChunk(nodeId, versionIndex, chunk);
          },
          // onComplete
          (versionIndex, metrics) => {
            get().completeParagraphVersion(nodeId, versionIndex, metrics);
          },
          // onError
          (versionIndex, error) => {
            get().setParagraphError(nodeId, versionIndex, error);
          }
        );
      },

      /**
       * 暂停生成
       */
      pauseGeneration: () => {
        console.log('⏸️ [ParagraphStore] Generation paused');
        set({ paused: true });
      },

      /**
       * 恢复生成
       */
      resumeGeneration: () => {
        console.log('▶️ [ParagraphStore] Generation resumed');
        set({ paused: false });
      },

      /**
       * 停止生成
       */
      stopGeneration: () => {
        console.log('⏹️ [ParagraphStore] Generation stopped');
        set({
          generating: false,
          paused: false,
          currentNodeId: null,
          pendingNodeIds: [],
        });
        paragraphGeneratorService.closeAllConnections();
      },

      /**
       * 追加段落片段
       */
      appendParagraphChunk: (nodeId, versionIndex, chunk) => {
        set((state) => {
          const paragraph = state.paragraphs[nodeId];
          if (!paragraph || !paragraph.versions[versionIndex]) {
            return state;
          }

          const updatedVersion = {
            ...paragraph.versions[versionIndex],
            content: paragraph.versions[versionIndex].content + chunk,
            wordCount: paragraph.versions[versionIndex].content.length + chunk.length,
          };

          const updatedVersions = [...paragraph.versions];
          updatedVersions[versionIndex] = updatedVersion;

          return {
            paragraphs: {
              ...state.paragraphs,
              [nodeId]: {
                ...paragraph,
                versions: updatedVersions,
                updatedAt: new Date().toISOString(),
              },
            },
          };
        });
      },

      /**
       * 完成段落版本生成
       */
      completeParagraphVersion: (nodeId, versionIndex, metrics) => {
        set((state) => {
          const paragraph = state.paragraphs[nodeId];
          if (!paragraph || !paragraph.versions[versionIndex]) {
            return state;
          }

          const aiScore =
            (metrics.relevance +
              metrics.readability +
              metrics.originality +
              metrics.coherence) /
            4;

          const updatedVersion = {
            ...paragraph.versions[versionIndex],
            generating: false,
            metrics,
            aiScore: Math.round(aiScore),
          };

          const updatedVersions = [...paragraph.versions];
          updatedVersions[versionIndex] = updatedVersion;

          // 如果是第一个完成的版本，自动选中
          const selectedIndex =
            paragraph.selectedVersionIndex === -1 ? versionIndex : paragraph.selectedVersionIndex;

          return {
            paragraphs: {
              ...state.paragraphs,
              [nodeId]: {
                ...paragraph,
                versions: updatedVersions,
                selectedVersionIndex: selectedIndex,
                updatedAt: new Date().toISOString(),
              },
            },
          };
        });

        console.log(`✅ [ParagraphStore] Version ${versionIndex} completed for node ${nodeId}`);
      },

      /**
       * 设置段落错误
       */
      setParagraphError: (nodeId, versionIndex, error) => {
        set((state) => {
          const paragraph = state.paragraphs[nodeId];
          if (!paragraph || !paragraph.versions[versionIndex]) {
            return state;
          }

          const updatedVersion = {
            ...paragraph.versions[versionIndex],
            generating: false,
            error,
          };

          const updatedVersions = [...paragraph.versions];
          updatedVersions[versionIndex] = updatedVersion;

          return {
            paragraphs: {
              ...state.paragraphs,
              [nodeId]: {
                ...paragraph,
                versions: updatedVersions,
                updatedAt: new Date().toISOString(),
              },
            },
          };
        });

        const errorMsg = typeof error === 'string' ? error : String(error);
        console.error(
          `❌ [ParagraphStore] Error in version ${versionIndex} for node ${nodeId}: ${errorMsg}`
        );
      },

      /**
       * 选择版本
       */
      selectVersion: (nodeId, versionIndex) => {
        set((state) => {
          const paragraph = state.paragraphs[nodeId];
          if (!paragraph) return state;

          return {
            paragraphs: {
              ...state.paragraphs,
              [nodeId]: {
                ...paragraph,
                selectedVersionIndex: versionIndex,
                updatedAt: new Date().toISOString(),
              },
            },
          };
        });

        console.log(`✅ [ParagraphStore] Selected version ${versionIndex} for node ${nodeId}`);
      },

      /**
       * 重新生成版本
       */
      regenerateVersion: async (nodeId, versionIndex, adjustments = {}) => {
        console.log('🔄 [ParagraphStore] Regenerating version:', {
          nodeId,
          versionIndex,
          adjustments,
        });

        set((state) => {
          const paragraph = state.paragraphs[nodeId];
          if (!paragraph) return state;

          const updatedVersions = [...paragraph.versions];
          updatedVersions[versionIndex] = {
            ...updatedVersions[versionIndex],
            generating: true,
            error: undefined,
          };

          return {
            paragraphs: {
              ...state.paragraphs,
              [nodeId]: {
                ...paragraph,
                versions: updatedVersions,
              },
            },
          };
        });

        try {
          const result = await paragraphGeneratorService.regenerateParagraph(
            nodeId,
            versionIndex,
            adjustments
          );

          set((state) => {
            const paragraph = state.paragraphs[nodeId];
            if (!paragraph) return state;

            const updatedVersions = [...paragraph.versions];
            updatedVersions[versionIndex] = {
              ...updatedVersions[versionIndex],
              content: result.content,
              generating: false,
              metrics: result.metrics,
              aiScore:
                (result.metrics.relevance +
                  result.metrics.readability +
                  result.metrics.originality +
                  result.metrics.coherence) /
                4,
              wordCount: result.content.length,
            };

            return {
              paragraphs: {
                ...state.paragraphs,
                [nodeId]: {
                  ...paragraph,
                  versions: updatedVersions,
                  updatedAt: new Date().toISOString(),
                },
              },
            };
          });

          console.log('✅ [ParagraphStore] Version regenerated successfully');
        } catch (error) {
          const errorMsg = error instanceof Error ? error.message : String(error);
          console.error(`❌ [ParagraphStore] Failed to regenerate version: ${errorMsg}`);
          get().setParagraphError(nodeId, versionIndex, 'Regeneration failed');
        }
      },

      /**
       * 混合多个版本
       */
      mixVersions: async (nodeId, selections) => {
        console.log('🎨 [ParagraphStore] Mixing versions:', { nodeId, selections });

        try {
          const mixedContent = await paragraphGeneratorService.mixVersions(nodeId, selections);

          set((state) => {
            const paragraph = state.paragraphs[nodeId];
            if (!paragraph) return state;

            const newVersion: ParagraphVersion = {
              content: mixedContent,
              strategy: 'mixed',
              generating: false,
              aiScore: 0,
              wordCount: mixedContent.length,
              metrics: {
                relevance: 0,
                readability: 0,
                originality: 0,
                coherence: 0,
              },
            };

            const updatedVersions = [...paragraph.versions, newVersion];

            return {
              paragraphs: {
                ...state.paragraphs,
                [nodeId]: {
                  ...paragraph,
                  versions: updatedVersions,
                  selectedVersionIndex: updatedVersions.length - 1,
                  updatedAt: new Date().toISOString(),
                },
              },
            };
          });

          console.log('✅ [ParagraphStore] Versions mixed successfully');
        } catch (error) {
          const errorMsg = error instanceof Error ? error.message : String(error);
          console.error(`❌ [ParagraphStore] Failed to mix versions: ${errorMsg}`);
        }
      },

      /**
       * 设置当前节点
       */
      setCurrentNode: (nodeId) => {
        set({ currentNodeId: nodeId });
      },

      /**
       * 清空所有段落
       */
      clearParagraphs: () => {
        set({
          paragraphs: {},
          currentNodeId: null,
          generating: false,
          paused: false,
          currentProgress: 0,
          pendingNodeIds: [],
        });
        console.log('🗑️ [ParagraphStore] All paragraphs cleared');
      },

      /**
       * 删除指定段落
       */
      removeParagraph: (nodeId) => {
        set((state) => {
          const { [nodeId]: removed, ...rest } = state.paragraphs;
          return { paragraphs: rest };
        });
        console.log('🗑️ [ParagraphStore] Paragraph removed:', nodeId);
      },
    }),
    {
      name: 'paragraph-storage',
      partialize: (state) => ({
        paragraphs: state.paragraphs,
      }),
    }
  )
);
